﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Web;
using System.IO;

namespace Twi.COMMON.Core
{
    public class TwiReflectionHelper
    {
        /// <summary>
        /// 根据dll文件名获取Assembly【找bin文件夹下的dll】
        /// </summary>
        /// <param name="dllName">dll文件名（带.dll后缀，如Twi.Pages.BIM.dll）</param>
        /// <returns></returns>
        public static Assembly GetAssemblyFromBin(string dllName)
        {
            string binPath = HttpRuntime.CodegenDir;
            string dllFullPath = binPath + dllName;
            if (File.Exists(dllFullPath))
            {
                throw new Exception("dll文件【"+dllName+"】不存在");
            }
            Assembly assembly = Assembly.LoadFrom(dllFullPath);
            return assembly;
        }

        /// <summary>
        /// 执行dll中的某个方法
        /// </summary>
        /// <param name="dllName">dll文件名（带.dll后缀，如Twi.Pages.BIM.dll）【找bin文件夹下的dll】</param>
        /// <param name="methodName"></param>
        /// <param name="dictParams"></param>
        /// <returns></returns>
        public static dynamic ExecuteMethod(string dllName, string className,string methodName, Dictionary<string, object> dictParams=null)
        {
            Assembly assembly = GetAssemblyFromBin(dllName);
            Type t = assembly.GetType(className);
            BindingFlags flags = (BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance );
            MethodInfo methodInfo = t.GetMethod(methodName,flags);
            ParameterInfo[] paras = methodInfo.GetParameters();
            //参数和赋值
            object[] objParas = null;
            if (paras.Length > 0)
            {
                objParas = new object[paras.Length];
            }
            for (int i = 0; i < paras.Length; i++)
            {
                ParameterInfo pi = paras[i];
                objParas[i] = dictParams[pi.Name];
            }

            //创建实例
            object obj = null;
            obj = Activator.CreateInstance(t);
            //执行方法
            dynamic dyReturn = methodInfo.Invoke(obj, objParas);
            return dyReturn;
        }

        /// <summary>
        /// 获取实体对象的键值对字典。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public static Dictionary<string, object> GetEnityKeyValuePairDict<T>(T entity)
        {
            Dictionary<string, object> dict = new Dictionary<string, object>();
            foreach (PropertyInfo pi in typeof(T).GetProperties())
            {
                dict.Add(pi.Name, pi.GetValue(entity,null));
            }
            return dict;
        }

    }
}
